package com.igoal.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.igoal.comparator.GoalEntryComparator;
import com.igoal.dto.GoalDTO;
import com.igoal.dto.UserDTO;
import com.igoal.entity.GoalStatusEnum;
import com.igoal.entity.TookTypeEnum;
import com.igoal.entity.UserGoalDone;
import com.igoal.service.CommonService;
import com.igoal.service.GoalEntryManager;
import com.igoal.service.GoalManager;
import com.igoal.service.MessageManager;
import com.igoal.service.UserManagerExt;
import com.igoal.service.paging.PageItem;
import com.igoal.service.paging.PagingService;
import com.igoal.web.model.BaseModel;
import com.igoal.web.model.GoalDetailModel;
import com.igoal.web.model.GoalInfoModel;

@Controller
@RequestMapping("/goal/detail.html")
public class GoalDetailController extends BaseController {

	@Autowired
	public void setGoalManager(GoalManager goalManager) {
		this.goalManager = goalManager;
	}

	@Autowired
	public void setUserManagerExt(UserManagerExt userManagerExt) {
		this.userManagerExt = userManagerExt;
	}

	@Autowired
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}

	@Autowired
	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}
	
	@Autowired
	public void setGoalEntryManager(GoalEntryManager goalEnryManager) {
		this.goalEntryManager = goalEnryManager;
	}
	
	public String getViewPrefix() {
		return BaseControllerDelegate.DEFAULT_VIEW_PREFIX;
	}

	@RequestMapping(method = RequestMethod.GET)
	public String showGoalDetail(ModelMap model, HttpServletRequest request,
			@RequestParam("id") Long goalId) {

		GoalDTO goalDetail = goalManager.getGoalByPrimaryKey(goalId);
		if (goalDetail == null) {
			return "redirect:/dashboard.html";
		}

		if (isLoginUser()) {
			UserDTO user = getUserSession();
			initModel(model, user, goalDetail);
		} else {
			initModel(model, null, goalDetail);
		}

		return getViewPrefix() + "goalDetail";
	}

	@SuppressWarnings({ "unchecked" })
	private void initModel(ModelMap modelMap, UserDTO user, GoalDTO goalDetail) {
		if (modelMap == null) {
			return;
		}
		
		GoalDetailModel model = new GoalDetailModel();
		simpleModelInitialize(user, model);

		Long goalId = goalDetail.getId();
		int numDoing = goalManager.countDoingUsers(goalId);
		int numDone = goalManager.countDoneUsers(goalId);
		model.setNumDoing(numDoing);
		model.setNumDone(numDone);
		model.setNumDo(numDoing + numDone);

		// initialize left zone
		model.setGoalDetail(goalDetail);
		List<PageItem<Long>> recentEntries = goalEntryManager.getRecentEntries(goalDetail, user);
		Collections.sort(recentEntries, new GoalEntryComparator(false));

		List<PageItem<Long>> result = new ArrayList<PageItem<Long>>();

		for (int index = 0; index < PagingService.MAX_ENTRIES && index < recentEntries.size(); index++) {
			result.add(recentEntries.get(index));
		}
		model.setRecentEntries(result);

		// common quote
		model.setFamousQuote(commonService.getRandomFamousQuote());

		// initialize do-users
		List<UserDTO> doUsers = goalManager.getRandomUsersDoGoal(goalId);
		model.setDoUsers(doUsers);

		// initialize user status of this goal
		if (user != null) {
			GoalStatusEnum goalStatus = goalManager.getGoalStatus(goalId);
			if (goalStatus == null || GoalStatusEnum.THINKING.equals(goalStatus)) {
				model.setGoalStatus(-1);
			} else if (GoalStatusEnum.DOING.equals(goalStatus)) {
				model.setGoalStatus(0);
			} else {
				model.setGoalStatus(1);
			}

			initPeopleYouMayKnow(user, model);
		} else {
			model.setGoalStatus(-1);
		}

		// initialize goal summary
		List<UserGoalDone> sols = goalEntryManager.getAllSolutions(goalId);
		GoalInfoModel goalInfo = new GoalInfoModel();
		goalInfo.setTotalDoing(numDoing);
		goalInfo.setTotalDone(numDone);
		goalInfo.setTotalSolution(sols.size());
		int averageTime = 0;
		for (UserGoalDone sol : sols) {
			int t = sol.getTookAmount();
			TookTypeEnum unit = sol.getTookType();
			if (TookTypeEnum.DAY.equals(unit)) {
				averageTime += t;
			} else if (TookTypeEnum.MONTH.equals(unit)) {
				averageTime += t * 30;
			} else if (TookTypeEnum.WEEK.equals(unit)) {
				averageTime += t * 7;
			} else if (TookTypeEnum.YEAR.equals(unit)) {
				averageTime += t * 365;
			}
		}
		if (sols.size() > 0) {
			averageTime /= sols.size();
		}
		goalInfo.setAverageTime(averageTime);

		model.setGoalInfo(goalInfo);

		applyModel(modelMap, model);
	}

	public void initTopPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

	public void initRightPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}

	public void initLeftPage(BaseModel model, HttpServletRequest request) {
		// TODO Auto-generated method stub
		
	}
}
